from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.html import format_html
from django.urls import reverse
from django.utils import timezone
from django.contrib import messages
from .models import User, Badge, UserBadge, UserMessage, SysInfo, TopPostPermission, AllowedEmail, PendingUserRegistration


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    list_display = ('user_id', 'email', 'nickname', 'institution', 'gender', 'register_time', 'last_login_time', 'is_active')
    list_filter = ('gender', 'register_time', 'is_active')
    search_fields = ('email', 'nickname', 'institution')
    ordering = ('-register_time',)
    list_display_links = ('user_id', 'email', 'nickname', 'institution', 'gender', 'register_time', 'last_login_time', 'is_active')
    
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal Information', {'fields': ('nickname', 'avatar', 'gender', 'signature', 'institution')}),
        ('Permission', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('Important Dates', {'fields': ('last_login', 'register_time', 'last_login_time')}),
    )
    
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'nickname', 'password1', 'password2'),
        }),
    )


@admin.register(Badge)
class BadgeAdmin(admin.ModelAdmin):
    list_display = ('badge_id', 'name', 'description', 'create_time')
    search_fields = ('name', 'description')
    ordering = ('-create_time',)
    list_display_links = ('badge_id', 'name', 'description', 'create_time')


@admin.register(UserBadge)
class UserBadgeAdmin(admin.ModelAdmin):
    list_display = ('user', 'badge', 'get_time', 'is_show')
    list_filter = ('is_show', 'get_time')
    search_fields = ('user__nickname', 'badge__name')
    ordering = ('-get_time',)
    list_display_links = ('user', 'badge', 'get_time', 'is_show')


@admin.register(UserMessage)
class UserMessageAdmin(admin.ModelAdmin):
    list_display = ('message_id', 'received_user_id', 'send_nick_name', 'message_type', 'status', 'create_time')
    list_filter = ('message_type', 'status', 'create_time')
    search_fields = ('received_user_id', 'send_nick_name', 'article_title')
    ordering = ('-create_time',)
    list_display_links = ('message_id', 'received_user_id', 'send_nick_name', 'message_type', 'status', 'create_time')


@admin.register(SysInfo)
class SysInfoAdmin(admin.ModelAdmin):
    list_display = ('sys_id', 'content')
    search_fields = ('sys_id', 'content')
    list_display_links = ('sys_id', 'content')


@admin.register(TopPostPermission)
class TopPostPermissionAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'is_active', 'granted_by', 'create_time', 'update_time')
    list_filter = ('is_active', 'create_time', 'update_time')
    search_fields = ('user__nickname', 'user__email', 'granted_by__nickname', 'description')
    ordering = ('-create_time',)
    list_display_links = ('id', 'user')
    
    fieldsets = (
        ('Basic Information', {
            'fields': ('user', 'is_active', 'description')
        }),
        ('Authorization Information', {
            'fields': ('granted_by',)
        }),
        ('Time Information', {
            'fields': ('create_time', 'update_time'),
            'classes': ('collapse',)
        }),
    )
    
    readonly_fields = ('create_time', 'update_time')
    
    def save_model(self, request, obj, form, change):
        if not change:
            obj.granted_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(AllowedEmail)
class AllowedEmailAdmin(admin.ModelAdmin):
    list_display = ('email', 'description', 'is_active', 'created_at', 'updated_at')
    list_filter = ('is_active', 'created_at')
    search_fields = ('email', 'description')
    ordering = ('-created_at',)
    list_display_links = ('email',)
    list_editable = ('is_active',)
    
    fieldsets = (
        (None, {'fields': ('email', 'description', 'is_active')}),
        ('Time Information', {'fields': ('created_at', 'updated_at'), 'classes': ('collapse',)}),
    )
    
    readonly_fields = ('created_at', 'updated_at')
    
    def get_readonly_fields(self, request, obj=None):
        if obj:
            return self.readonly_fields + ('email',)
        return self.readonly_fields


@admin.register(PendingUserRegistration)
class PendingUserRegistrationAdmin(admin.ModelAdmin):
    list_display = ('id', 'email', 'nickname', 'institution', 'status_display', 'support_image_preview', 'created_at', 'reviewed_at', 'reviewed_by', 'action_buttons')
    list_filter = ('status', 'created_at', 'reviewed_at')
    search_fields = ('email', 'nickname', 'institution')
    ordering = ('-created_at',)
    list_display_links = ('id', 'email', 'nickname')
    readonly_fields = ('password', 'created_at', 'reviewed_at', 'reviewed_by', 'support_image_display')
    
    fieldsets = (
        ('Application Information', {
            'fields': ('email', 'nickname', 'password', 'institution', 'support', 'support_image_display')
        }),
        ('Review Information', {
            'fields': ('status', 'reject_reason', 'reviewed_at', 'reviewed_by'),
            'classes': ('collapse',)
        }),
        ('Time Information', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )

    def support_image_preview(self, obj):
        """在列表页显示证明图片"""
        if obj.support:
            return format_html(
                '''
                <div style="position: relative; display: inline-block;">
                    <img src="{}"
                         onclick="showImageModal(this.src)"
                         style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px; cursor: zoom-in; border: 1px solid #ddd;" />
                </div>
                <script>
                if (!window.showImageModal) {{
                    window.showImageModal = function(src) {{
                        var modal = document.createElement('div');
                        modal.style.position = 'fixed';
                        modal.style.top = '0';
                        modal.style.left = '0';
                        modal.style.width = '100%';
                        modal.style.height = '100%';
                        modal.style.backgroundColor = 'rgba(0,0,0,0.8)';
                        modal.style.display = 'flex';
                        modal.style.alignItems = 'center';
                        modal.style.justifyContent = 'center';
                        modal.style.zIndex = '9999';
                        modal.innerHTML = '<img src="' + src + '" style="max-width: 90%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px #000; cursor: zoom-out;" />';
                        modal.onclick = function() {{
                            document.body.removeChild(modal);
                        }};
                        document.body.appendChild(modal);
                    }}
                }}
                </script>
                ''',
                obj.support
            )
        return '-'

    support_image_preview.short_description = 'Support Image'
    support_image_preview.allow_tags = True

    def support_image_display(self, obj):
        """在详情页显示证明图片"""
        if obj.support:
            return format_html(
                '''
                <div style="margin: 10px 0;">
                    <p><strong>Support Document Image:</strong></p>
                    <img src="{}" onclick="showImageModal(this.src)" 
                         style="max-width: 400px; max-height: 300px; border: 1px solid #ddd; border-radius: 4px; cursor: zoom-in;" />
                    <p style="margin-top: 5px; color: #666; font-size: 12px;">
                        Image URL: <a href="{}" target="_blank">{}</a>
                    </p>
                </div>
                <script>
                function showImageModal(src) {{
                    var modal = document.createElement('div');
                    modal.style.position = 'fixed';
                    modal.style.top = '0';
                    modal.style.left = '0';
                    modal.style.width = '100%';
                    modal.style.height = '100%';
                    modal.style.backgroundColor = 'rgba(0,0,0,0.8)';
                    modal.style.display = 'flex';
                    modal.style.alignItems = 'center';
                    modal.style.justifyContent = 'center';
                    modal.style.zIndex = '9999';
                    modal.innerHTML = '<img src="' + src + '" style="max-width: 90%; max-height: 90%; border-radius: 8px; box-shadow: 0 0 20px #000; cursor: zoom-out;" />';
                    modal.onclick = function() {{
                        document.body.removeChild(modal);
                    }};
                    document.body.appendChild(modal);
                }}
                </script>
                ''',
                obj.support,
                obj.support,
                obj.support
            )
        return 'No support image provided'

    support_image_display.short_description = 'Support Document'
    support_image_display.allow_tags = True
    
    def status_display(self, obj):
        """显示状态的彩色标签"""
        colors = {
            0: '#ffc107',  # 黄色 - 待审核
            1: '#28a745',  # 绿色 - 已批准
            2: '#dc3545',  # 红色 - 已拒绝
        }
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            colors.get(obj.status, '#6c757d'),
            obj.get_status_display()
        )
    status_display.short_description = 'Status'
    
    def action_buttons(self, obj):
        """显示操作按钮"""
        if obj.status == 0:  # 只有待审核状态才显示操作按钮
            approve_url = reverse('admin:approve_registration', args=[obj.pk])
            reject_url = reverse('admin:reject_registration', args=[obj.pk])
            return format_html(
                '<a class="button" href="{}" style="background-color: #28a745; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px; margin-right: 5px;">Approve</a>'
                '<a class="button" href="{}" style="background-color: #dc3545; color: white; padding: 5px 10px; text-decoration: none; border-radius: 3px;">Reject</a>',
                approve_url, reject_url
            )
        return '-'
    action_buttons.short_description = 'Actions'
    action_buttons.allow_tags = True
    
    def get_urls(self):
        """添加自定义URL"""
        from django.urls import path
        urls = super().get_urls()
        custom_urls = [
            path('<int:registration_id>/approve/', self.admin_site.admin_view(self.approve_registration), name='approve_registration'),
            path('<int:registration_id>/reject/', self.admin_site.admin_view(self.reject_registration), name='reject_registration'),
        ]
        return custom_urls + urls
    
    def approve_registration(self, request, registration_id):
        """批准注册申请"""
        from django.shortcuts import redirect, get_object_or_404
        from django.http import HttpResponseRedirect
        
        registration = get_object_or_404(PendingUserRegistration, pk=registration_id)
        
        if registration.status != 0:
            messages.error(request, f'Registration application has already been {registration.get_status_display().lower()}')
            return redirect('admin:users_pendinguserregistration_changelist')
        
        try:
            # 批准申请
            user = registration.approve(request.user)
            messages.success(request, f'Registration application for {registration.email} has been approved successfully. User created: {user.nickname}')
        except Exception as e:
            messages.error(request, f'Failed to approve registration: {str(e)}')
        
        return redirect('admin:users_pendinguserregistration_changelist')
    
    def reject_registration(self, request, registration_id):
        """拒绝注册申请"""
        from django.shortcuts import redirect, get_object_or_404
        
        registration = get_object_or_404(PendingUserRegistration, pk=registration_id)
        
        if registration.status != 0:
            messages.error(request, f'Registration application has already been {registration.get_status_display().lower()}')
            return redirect('admin:users_pendinguserregistration_changelist')
        
        if request.method == 'POST':
            reason = request.POST.get('reason', '')
            try:
                registration.reject(request.user, reason)
                messages.success(request, f'Registration application for {registration.email} has been rejected')
                return redirect('admin:users_pendinguserregistration_changelist')
            except Exception as e:
                messages.error(request, f'Failed to reject registration: {str(e)}')
        
        # 显示拒绝原因输入页面
        from django.shortcuts import render
        return render(request, 'admin/users/reject_registration.html', {
            'registration': registration,
            'title': f'Reject Registration - {registration.email}',
        })
    
    def has_add_permission(self, request):
        """禁止在后台直接添加注册申请"""
        return False